<!--
  播放控制器组件
  提供播放、暂停、停止等控制功能
-->
<template>
  <div
    class="playback-controls"
    :class="{ 'draggable': isDragMode, 'dragging': isDragging }"
    :style="controlsStyle"
    @mousedown="handleMouseDown"
  >
    <div class="controls-container">
      <!-- 主要控制按钮 -->
      <div class="main-controls">
        <n-button-group>
          <!-- 跳到开始 -->
          <n-button 
            quaternary 
            @click="seekToStart"
            :disabled="currentTime === 0"
          >
            <template #icon>
              <n-icon><PlaySkipBackOutline /></n-icon>
            </template>
          </n-button>
          
          <!-- 后退 -->
          <n-button 
            quaternary 
            @click="stepBackward"
          >
            <template #icon>
              <n-icon><PlayBackOutline /></n-icon>
            </template>
          </n-button>
          
          <!-- 播放/暂停 -->
          <n-button 
            type="primary"
            @click="togglePlayback"
            size="large"
          >
            <template #icon>
              <n-icon size="20">
                <component :is="isPlaying ? PauseOutline : PlayOutline" />
              </n-icon>
            </template>
          </n-button>
          
          <!-- 前进 -->
          <n-button 
            quaternary 
            @click="stepForward"
          >
            <template #icon>
              <n-icon><PlayForwardOutline /></n-icon>
            </template>
          </n-button>
          
          <!-- 跳到结束 -->
          <n-button 
            quaternary 
            @click="seekToEnd"
            :disabled="currentTime === totalDuration"
          >
            <template #icon>
              <n-icon><PlaySkipForwardOutline /></n-icon>
            </template>
          </n-button>
        </n-button-group>
      </div>
      
      <!-- 时间显示 -->
      <div class="time-display">
        <n-text class="time-text">
          {{ formatTime(currentTime) }} / {{ formatTime(totalDuration) }}
        </n-text>
      </div>
      
      <!-- 辅助控制 -->
      <div class="aux-controls">
        <!-- 循环播放 -->
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button 
              quaternary 
              @click="toggleLoop"
              :type="loop ? 'primary' : 'default'"
            >
              <template #icon>
                <n-icon><RepeatOutline /></n-icon>
              </template>
            </n-button>
          </template>
          {{ loop ? '关闭循环' : '开启循环' }}
        </n-tooltip>
        
        <!-- 播放速度 -->
        <n-dropdown 
          :options="speedOptions" 
          @select="handleSpeedSelect"
          trigger="click"
        >
          <n-button quaternary style="width: 86px">
            <template #icon>
              <n-icon><SpeedometerOutline /></n-icon>
            </template>
            {{ playbackSpeed }}x
          </n-button>
        </n-dropdown>
        
        <!-- 音量控制 -->
        <n-popover trigger="click" placement="top">
          <template #trigger>
            <n-button quaternary>
              <template #icon>
                <n-icon>
                  <component :is="getVolumeIcon()" />
                </n-icon>
              </template>
            </n-button>
          </template>
          
          <div class="volume-control">
            <n-slider
              v-model:value="volume"
              :min="0"
              :max="100"
              :step="1"
              vertical
              style="height: 100px;"
              @update:value="handleVolumeChange"
            />
            <n-text depth="3" style="text-align: center; margin-top: 8px;">
              {{ volume }}%
            </n-text>
          </div>
        </n-popover>

        <!-- 拖动/锁定按钮 -->
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button
              quaternary
              size="small"
              @click="toggleDragMode"
              :type="isDragMode ? 'primary' : 'default'"
            >
              <template #icon>
                <n-icon size="14">
                  <component :is="isDragMode ? LockOpenOutline : LockClosedOutline" />
                </n-icon>
              </template>
            </n-button>
          </template>
          {{ isDragMode ? '锁定位置' : '解锁拖动' }}
        </n-tooltip>
      </div>
    </div>
    
    <!-- 进度条 -->
    <div class="progress-container">
      <n-slider
        v-model:value="currentTime"
        :min="0"
        :max="totalDuration"
        :step="0.1"
        :format-tooltip="formatTime"
        @update:value="handleSeek"
        class="progress-slider"
      />
    </div>
    
    <!-- 快捷键提示 -->
    <div v-if="showShortcuts" class="shortcuts-hint">
      <n-text depth="3" style="font-size: 12px;">
        空格: 播放/暂停 | ←→: 逐帧 | Home/End: 开始/结束
      </n-text>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import {
  NButton,
  NButtonGroup,
  NIcon,
  NText,
  NTooltip,
  NDropdown,
  NPopover,
  NSlider
} from 'naive-ui'
import {
  PlayOutline,
  PauseOutline,
  PlaySkipBackOutline,
  PlaySkipForwardOutline,
  PlayBackOutline,
  PlayForwardOutline,
  RepeatOutline,
  SpeedometerOutline,
  VolumeHighOutline,
  VolumeMediumOutline,
  VolumeLowOutline,
  VolumeOffOutline,
  LockClosedOutline,
  LockOpenOutline
} from '@vicons/ionicons5'
import { useEditorStore } from '../../stores/editor'

// 事件定义
const emit = defineEmits(['play', 'pause', 'stop'])

// 状态管理
const editorStore = useEditorStore()

// 本地状态
const volume = ref(80)
const showShortcuts = ref(false)

// 拖动相关状态
const isDragMode = ref(false)
const isDragging = ref(false)
const position = ref({ x: 0, y: 0 })
const dragStart = ref({ x: 0, y: 0 })
const initialPosition = ref({ x: 0, y: 0 })

// 全新方案：使用CSS变量直接控制位置
let startX = 0
let startY = 0
let currentX = 0
let currentY = 0

// 计算属性
const isPlaying = computed(() => editorStore.playback.isPlaying)
const currentTime = computed({
  get: () => editorStore.playback.currentTime,
  set: (value) => editorStore.seekTo(value)
})
const totalDuration = computed(() => editorStore.playback.totalDuration)
const playbackSpeed = computed(() => editorStore.playback.playbackSpeed)
const loop = computed(() => editorStore.playback.loop)

// 控制面板样式 - 简化版本
const controlsStyle = computed(() => {
  return {
    width: '715px',
    minWidth: '715px',
    // 只在非拖动状态下使用Vue的transform
    ...(position.value.x !== 0 || position.value.y !== 0 ? {
      transform: `translate3d(${position.value.x}px, ${position.value.y}px, 0)`,
      position: 'relative'
    } : {})
  }
})

// 播放速度选项
const speedOptions = [
  { label: '0.25x', key: 0.25 },
  { label: '0.5x', key: 0.5 },
  { label: '0.75x', key: 0.75 },
  { label: '1x', key: 1 },
  { label: '1.25x', key: 1.25 },
  { label: '1.5x', key: 1.5 },
  { label: '2x', key: 2 }
]

// 方法
const togglePlayback = () => {
  if (isPlaying.value) {
    emit('pause')
  } else {
    emit('play')
  }
}

const seekToStart = () => {
  editorStore.seekTo(0)
}

const seekToEnd = () => {
  editorStore.seekTo(totalDuration.value)
}

const stepBackward = () => {
  const newTime = Math.max(0, currentTime.value - 0.1)
  editorStore.seekTo(newTime)
}

const stepForward = () => {
  const newTime = Math.min(totalDuration.value, currentTime.value + 0.1)
  editorStore.seekTo(newTime)
}

const toggleLoop = () => {
  editorStore.playback.loop = !editorStore.playback.loop
}

const handleSpeedSelect = (speed: number) => {
  editorStore.playback.playbackSpeed = speed
}

const handleSeek = (time: number) => {
  editorStore.seekTo(time)
}

const handleVolumeChange = (newVolume: number) => {
  volume.value = newVolume
  // TODO: 实际的音量控制逻辑
}

const getVolumeIcon = () => {
  if (volume.value === 0) return VolumeOffOutline
  if (volume.value < 30) return VolumeLowOutline
  if (volume.value < 70) return VolumeMediumOutline
  return VolumeHighOutline
}

const formatTime = (seconds: number): string => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  const ms = Math.floor((seconds % 1) * 10)
  return `${mins}:${secs.toString().padStart(2, '0')}.${ms}`
}

// 拖动相关方法
const toggleDragMode = () => {
  isDragMode.value = !isDragMode.value
  // 锁定时保持当前位置，不重置
}

const handleMouseDown = (event: MouseEvent) => {
  if (!isDragMode.value) return

  const element = event.currentTarget as HTMLElement

  // 设置拖动状态
  isDragging.value = true

  // 确保当前位置在边界内
  const constrainedPos = constrainPosition(position.value.x, position.value.y)
  position.value = constrainedPos

  // 记录起始位置
  startX = event.clientX - position.value.x
  startY = event.clientY - position.value.y

  // 启用GPU加速
  element.style.willChange = 'transform'
  element.style.transform = `translate3d(${position.value.x}px, ${position.value.y}px, 0)`

  // 添加事件监听
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)

  event.preventDefault()
}

// 边界限制函数
const constrainPosition = (x: number, y: number) => {
  const controlsWidth = 715
  const controlsHeight = 100 // 估算控制器高度

  // 获取视口尺寸
  const viewportWidth = window.innerWidth
  const viewportHeight = window.innerHeight

  // 计算边界
  const minX = -controlsWidth / 2 + 50 // 左边界，保留50px可见
  const maxX = viewportWidth - controlsWidth / 2 - 50 // 右边界，保留50px可见
  const minY = -controlsHeight / 2 + 30 // 上边界，保留30px可见
  const maxY = viewportHeight - controlsHeight / 2 - 30 // 下边界，保留30px可见

  return {
    x: Math.max(minX, Math.min(maxX, x)),
    y: Math.max(minY, Math.min(maxY, y))
  }
}

// 全新方案：使用GPU加速的transform3d
const handleMouseMove = (event: MouseEvent) => {
  if (!isDragging.value || !isDragMode.value) return

  // 计算新位置
  const rawX = event.clientX - startX
  const rawY = event.clientY - startY

  // 应用边界限制
  const constrainedPos = constrainPosition(rawX, rawY)
  currentX = constrainedPos.x
  currentY = constrainedPos.y

  // 直接更新所有拖动元素的transform
  const elements = document.querySelectorAll('.playback-controls.draggable')
  elements.forEach(element => {
    (element as HTMLElement).style.transform = `translate3d(${currentX}px, ${currentY}px, 0)`
  })

  // 更新Vue状态
  position.value = { x: currentX, y: currentY }
}

const handleMouseUp = () => {
  isDragging.value = false

  // 清理GPU加速
  const elements = document.querySelectorAll('.playback-controls')
  elements.forEach(element => {
    (element as HTMLElement).style.willChange = 'auto'
  })

  // 移除事件监听器
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
}

// 窗口大小改变时重新检查边界
const handleWindowResize = () => {
  if (position.value.x !== 0 || position.value.y !== 0) {
    const constrainedPos = constrainPosition(position.value.x, position.value.y)
    position.value = constrainedPos
  }
}

// 键盘快捷键
const handleKeydown = (event: KeyboardEvent) => {
  // 防止在输入框中触发
  if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
    return
  }
  
  switch (event.code) {
    case 'Space':
      event.preventDefault()
      togglePlayback()
      break
    case 'ArrowLeft':
      event.preventDefault()
      stepBackward()
      break
    case 'ArrowRight':
      event.preventDefault()
      stepForward()
      break
    case 'Home':
      event.preventDefault()
      seekToStart()
      break
    case 'End':
      event.preventDefault()
      seekToEnd()
      break
    case 'KeyL':
      if (event.ctrlKey || event.metaKey) {
        event.preventDefault()
        toggleLoop()
      }
      break
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
  window.addEventListener('resize', handleWindowResize)

  // 显示快捷键提示
  setTimeout(() => {
    showShortcuts.value = true
    setTimeout(() => {
      showShortcuts.value = false
    }, 3000)
  }, 1000)
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeydown)
  window.removeEventListener('resize', handleWindowResize)
  // 清理拖动事件监听器
  document.removeEventListener('mousemove', handleMouseMove, { passive: false } as any)
  document.removeEventListener('mouseup', handleMouseUp, { passive: false } as any)
})
</script>

<style lang="scss" scoped>
.playback-controls {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px;
  color: white;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  min-width: 715px;
  transition: all 0.2s ease;

  /* GPU加速优化 */
  transform: translateZ(0);
  backface-visibility: hidden;
  perspective: 1000px;

  &.draggable {
    cursor: move;
    border-color: var(--primary-color);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), 0 0 0 2px var(--primary-color);
    width: 715px;
    min-width: 715px;
    will-change: transform; /* 提前告知浏览器将要变换 */
  }

  &.dragging {
    z-index: 1000;
    box-shadow: 0 12px 48px rgba(0, 0, 0, 0.5), 0 0 0 2px var(--primary-color);
    width: 715px;
    min-width: 715px;
    max-width: 715px;
    will-change: transform; /* GPU加速 */
    transform-style: preserve-3d; /* 3D变换优化 */
  }
}

.controls-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 12px;
}

.main-controls {
  display: flex;
  align-items: center;
}

.time-display {
  .time-text {
    font-family: monospace;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.9);
  }
}

.aux-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-container {
  margin-bottom: 8px;
  
  .progress-slider {
    :deep(.n-slider-rail) {
      background: rgba(255, 255, 255, 0.2);
    }
    
    :deep(.n-slider-fill) {
      background: var(--primary-color);
    }
    
    :deep(.n-slider-handle) {
      border-color: var(--primary-color);
      background: white;
    }
  }
}

.volume-control {
  padding: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  
  :deep(.n-slider-rail) {
    background: rgba(0, 0, 0, 0.1);
  }
  
  :deep(.n-slider-fill) {
    background: var(--primary-color);
  }
}

.shortcuts-hint {
  text-align: center;
  opacity: 0.7;
  animation: fadeInOut 3s ease-in-out;
}

@keyframes fadeInOut {
  0%, 100% {
    opacity: 0;
  }
  20%, 80% {
    opacity: 0.7;
  }
}

// 深色主题下的按钮样式
:deep(.n-button) {
  &.n-button--quaternary {
    color: rgba(255, 255, 255, 0.8);
    
    &:hover {
      color: white;
      background: rgba(255, 255, 255, 0.1);
    }
    
    &:active {
      background: rgba(255, 255, 255, 0.2);
    }
  }
  
  &.n-button--primary {
    background: var(--primary-color);
    border-color: var(--primary-color);
    
    &:hover {
      background: var(--primary-color-hover);
      border-color: var(--primary-color-hover);
    }
  }
}

:deep(.n-dropdown) {
  .n-dropdown-menu {
    background: rgba(0, 0, 0, 0.9);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .n-dropdown-option {
    color: rgba(255, 255, 255, 0.8);
    
    &:hover {
      background: rgba(255, 255, 255, 0.1);
      color: white;
    }
  }
}

:deep(.n-popover) {
  .n-popover__content {
    background: rgba(0, 0, 0, 0.9);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
}
</style>
